package com.hbwxz.es.learning;


import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.io.IOException;

public class ESLearning {
    public static void main(String[] args) throws IOException {
        //RestHighLevelClient 一直是比较流行的，很多项目是在他 deprecated之前写的
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200))
        );
        //真正的进行搜索了
        SearchRequest request = new SearchRequest().indices("test");
        //查询的构建
        SearchSourceBuilder sourceBuilder1 = new SearchSourceBuilder();
        //修改处
        sourceBuilder1.query(QueryBuilders.matchAllQuery()).from(0).size(2).sort("age", SortOrder.ASC);
        request.source(sourceBuilder1);
        SearchResponse response1 = client.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = response1.getHits().getHits();
        for(SearchHit hit : hits) {
            System.out.println("输出数据 1 " + " = " + hit.getSourceAsString());
        }

        //记录最后一条查询出来的数据 !!!
        SearchHit result = hits[hits.length - 1];
        SearchSourceBuilder sourceBuilder2 = new SearchSourceBuilder();
        sourceBuilder2.query(QueryBuilders.matchAllQuery()).size(2).sort("age", SortOrder.ASC);
        sourceBuilder2.searchAfter(result.getSortValues());
        SearchRequest request2 = new SearchRequest().indices("test");
        request2.source(sourceBuilder2);
        SearchResponse search = client.search(request2, RequestOptions.DEFAULT);
        for(SearchHit hit : search.getHits()) {
            System.out.println("输出数据2" + " = " + hit.getSourceAsString());
        }
        client.close();
    }
}
